import { store } from "@/store";
import { usePermissionStoreHook } from "@/store/modules/permission.store";
import { useDictStoreHook } from "@/store/modules/dict.store";

import AuthAPI from "@/api/auth.api";
// import UserAPI from "@/api/system/user.api";

// import { setAccessToken, setRefreshToken, getRefreshToken, clearToken } from "@/utils/auth";
import { setAccessToken, clearToken } from "@/utils/auth";

export const useUserStore = defineStore("user", () => {
  const userInfo = useStorage("userInfo", {});

  /**
   * 登录
   *
   * @param {Object} LoginFormData
   * @returns
   */
  function login(LoginFormData) {
    return new Promise((resolve, reject) => {
      AuthAPI.login(LoginFormData)
        .then((data) => {
          // const { token, refreshToken } = data;
          console.log('token', data.data.user);

          setAccessToken(data.data.token.token); // eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          Object.assign(userInfo.value, { ...data.data.user });
          console.log('userInfo', userInfo.value);
          // setRefreshToken(refreshToken);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }


  /**
   * 登出
   */
  function logout() {
    clearSessionAndCache();
    resolve();

  }

  /**
   * 清除用户会话和缓存
   */
  function clearSessionAndCache() {
    return new Promise((resolve) => {
      clearToken();
      usePermissionStoreHook().resetRouter();
      useDictStoreHook().clearDictCache();
      userInfo.value = {};
      resolve()
    });
  }

  return {
    userInfo,
    login,
    logout,
    clearSessionAndCache,

  };
});

/**
 * 用于在组件外部（如在Pinia Store 中）使用 Pinia 提供的 store 实例。
 * 官方文档解释了如何在组件外部使用 Pinia Store：
 * https://pinia.vuejs.org/core-concepts/outside-component-usage.html#using-a-store-outside-of-a-component
 */
export function useUserStoreHook() {
  return useUserStore(store);
} 
